package com.zou.lotterylucky.utils

import android.content.Context
import android.content.SharedPreferences
import com.v2.utils.TApp

/**
 * SharedPreferences的一个工具类，调用setParam就能保存String, Integer, Boolean, Float, Long类型的参数
 * 同样调用getParam就能获取到保存在手机里面的数据
 *
 * @author xiaanming
 */
object SPUtils {
    /**
     * 保存在手机里面的文件名
     */
    private const val FILE_NAME = "share_date"

    private var sp: SharedPreferences? = null

    private var editor: SharedPreferences.Editor? = null

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param context context
     * @param key     key
     * @param object  obj
     */
    operator fun set(key: String, `object`: Any) {
        set(TApp.getInstance(), key, `object`)
    }

    operator fun set(context: Context, key: String, `object`: Any) {

        val type = `object`.javaClass.simpleName
        if (sp == null) {
            sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        }
        if (editor == null) {
            editor = sp!!.edit()
        }

        when (type) {
            "String" -> {
                editor!!.putString(key, `object` as String)
            }
            "Integer" -> {
                editor!!.putInt(key, `object` as Int)
            }
            "Boolean" -> {
                editor!!.putBoolean(key, `object` as Boolean)
            }
            "Float" -> {
                editor!!.putFloat(key, `object` as Float)
            }
            "Long" -> {
                editor!!.putLong(key, `object` as Long)
            }
        }

        editor!!.apply()
    }


    operator fun get(key: String, defaultObject: Any): Any? {
        return get(TApp.getInstance(), key, defaultObject)
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    operator fun get(context: Context, key: String, defaultObject: Any): Any? {
        val type = defaultObject.javaClass.simpleName
        if (sp == null) {
            sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        }

        when (type) {
            "String" -> {
                return sp!!.getString(key, defaultObject as String)
            }
            "Integer" -> {
                return sp!!.getInt(key, defaultObject as Int)
            }
            "Boolean" -> {
                return sp!!.getBoolean(key, defaultObject as Boolean)
            }
            "Float" -> {
                return sp!!.getFloat(key, defaultObject as Float)
            }
            "Long" -> {
                return sp!!.getLong(key, defaultObject as Long)
            }
            else -> return null
        }

    }


    fun clear(context: Context) {
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        sp.edit().clear().apply()
    }
}  